import os
import shutil
import sys
from configparser import ConfigParser


class FileManager:
    def __init__(self):
        self.base_path = os.path.dirname(os.path.realpath(sys.argv[0]))
        self.input_path = self.get_default_input()['path']

    def get_path_tree(self, path=None):
        path_map = {}
        if not path:
            path = self.input_path
        if os.path.isfile(path) and os.path.exists(path):
            path_map[os.path.basename(path)] = path
        elif os.path.isdir(path) and os.path.exists(path):
            path_map[os.path.basename(path)] = []
            for filename in os.listdir(path):
                file_path = os.path.join(path, filename)
                path_map[os.path.basename(path)].append(self.get_path_tree(file_path))
        return path_map

    def get_path_list(self, path=None):
        path_list = []
        if not path:
            path = self.input_path
        if os.path.isfile(path) and os.path.exists(path):
            path_list.append(path)
        elif os.path.isdir(path) and os.path.exists(path):
            for filename in os.listdir(path):
                file_path = os.path.join(path, filename)
                path_list.extend(self.get_path_list(file_path))
        return path_list

    def remove_path(self, path=None):
        if not path:
            path = self.input_path
        if os.path.isdir(path) and os.path.exists(path):
            shutil.rmtree(path)
        elif os.path.isfile(path) and os.path.exists(path):
            os.remove(path)
        else:
            raise Exception('The path must be a file or folder')

    def remove_path_content(self, folder_path=None):
        if not folder_path:
            folder_path = self.input_path
        try:
            if os.path.isdir(folder_path) and os.path.exists(folder_path):
                for filename in os.listdir(folder_path):
                    file_path = os.path.join(folder_path, filename)
                    self.remove_path(file_path)
            elif os.path.isfile(folder_path) and os.path.exists(folder_path):
                os.remove(folder_path)
        except Exception as e:
            print(f"删除文件夹 {folder_path} 时出错: {e}")

    def get_default_input(self):
        conf = ConfigParser()
        conf.read(os.path.join(self.base_path, 'config/config.ini'))
        return conf['input']


if __name__ == '__main__':
    input_path = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'input')
    print(input_path)
    fm = FileManager()
    # fm.remove_path_content()
    # fm.remove_path()
    res = fm.get_path_tree()
    print(res)
    res = fm.get_path_list('/Users/fengwensen/projects/code_analysis/input/b.py')
    print(res)
